package com.lemon.blog.system.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.lemon.common.core.exception.UtilException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * 包名称：com.lemon.blog.utils
 * 类名称：AliyunOSSUtil
 * 类描述：阿里云OSS工具类
 * 创建人：@author huangpeng
 * 创建时间：2022年04月10日 00:14
 */
@Component
public class AliyunOSSUtil {

    @Value("${aliyunOss.endpoint}")
    private String endpoint;

    @Value("${aliyunOss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyunOss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyunOss.bucketName}")
    private String bucketName;

    @Value("${aliyunOss.urlPrefix}")
    private String urlPrefix;

    /**
     * 上传文件，以IO流方式
     *
     * @param inputStream 输入流
     * @param objectName  唯一objectName（在oss中的文件名字）
     * @return url 文件链接
     */
    public String upload(InputStream inputStream, String objectName) {
        String fileUrl = "";
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）
            ossClient.putObject(bucketName, objectName, inputStream);
            // 关闭OSSClient
            ossClient.shutdown();
            // 上传成功
            fileUrl = urlPrefix + "/" + objectName;
        } catch (Exception e) {
            //上传失败
            e.printStackTrace();
            throw new UtilException("文件上传失败！", e);
        }
        return fileUrl;
    }

    /**
     * 删除OSS中的单个文件
     *
     * @param objectName 唯一objectName（在oss中的文件名字）
     */
    public void delete(String objectName) {
        try {
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 删除文件
            ossClient.deleteObject(bucketName, objectName);
            // 关闭OSSClient
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除OSS中的文件
     *
     * @param objectNames oss中文件名list
     */
    public void delete(List<String> objectNames) {
        try {
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 批量删除文件
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(objectNames));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            // 关闭OSSClient
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件临时url
     *
     * @param objectName oss中的文件名
     * @param effectiveTime 有效时间(ms)
     */
    public String getUrl(String objectName,long effectiveTime){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 设置URL过期时间
        Date expiration = new Date(System.currentTimeMillis() + effectiveTime);
        GeneratePresignedUrlRequest generatePresignedUrlRequest ;
        generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, objectName);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }

}
